package com.luoqiz.project.copyDir;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class FileOper {

	/**
	 * 拷贝文件夹
	 */
	@Test
	public void copyDir(String srcDirPath,String destDirPath) {
//		String srcDirPath = "d:/dome/src";
//		String destDirPath = "d:/dome/dest";
		List<String> files = new ArrayList<String>();
		listFiles(srcDirPath, files);
		files.forEach((s) -> {
			// System.out.println(s);
			copyFile(s.substring(srcDirPath.length() + 1), srcDirPath, destDirPath);
		});
	}

	/**
	 * 获取文件夹内所有的文件
	 * 
	 * @param dir
	 * @param files
	 * @return
	 */
	public List<String> listFiles(String dir, List<String> files) {
		if (dir == null) {
			return null;
		}

		File srcPath = new File(dir);
		if (srcPath.exists() && srcPath.isDirectory()) {
			File[] listFiles = srcPath.listFiles();
			for (File list : listFiles) {
				if (list.isFile()) {
					files.add(list.getAbsolutePath());
				} else if (list.isDirectory()) {
					listFiles(list.getAbsolutePath(), files);
				} else {
				}
			}
		}
		return files;
	}

	/**
	 * 拷贝文件
	 * 
	 * @param srcPath
	 * @param destDirPath
	 * @param destDirPath
	 */
	private void copyFile(String srcFileName, String srcDirPath, String destDirPath) {
		if (srcFileName == null || destDirPath == null) {
			return;
		}
		try {
			File srcFile = new File(srcDirPath + "/" + srcFileName);
			FileInputStream fis = new FileInputStream(srcFile);
			File destFile = new File(destDirPath + "/" + srcFileName);
			File temp = new File(destFile.getParentFile().toString());
			
			if (!temp.exists()) {
				temp.mkdirs();
			}
			
			FileOutputStream fos = new FileOutputStream(destFile);
			byte[] b = new byte[1024];
			int len = -1;
			try {
				while ((len = fis.read(b)) != -1) {
					fos.write(b, 0, len);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					fis.close();
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
